package net.xi.dmhome.controller;

import cn.hutool.core.map.MapUtil;
import net.xi.dmhome.Utils.DesAesUtil;
import net.xi.dmhome.entity.User;
import net.xi.dmhome.handler.Result;
import net.xi.dmhome.mapper.UserMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: jxhu
 * @Description:管理登录
 * @Date Created in 2021-02-03 11:23
 * @Modified By:
 */

@RestController
@RequestMapping("/register")
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    public Result registLogin(@RequestBody User user, HttpServletResponse response) throws Exception {
        //获取当前用户
        Subject currentUser = SecurityUtils.getSubject();

        /* @Description: 得到的密码先进行加密访问数据库,@Param:  */
        String password = DesAesUtil.desaes(user.getPassword());

        //把用户名和密码封装成一个令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), password);
        String stoken =  token.toString();
        try {
            currentUser.login(token);
            //获取从shiro的session里存的User类
            User loginUser = (User) currentUser.getSession().getAttribute("loginUser");

            response.setHeader("Authorization",stoken);
            response.setHeader("Access-control-Expose-Headers","Authorization");
            return Result.success(200,"success", MapUtil.builder()
                                                                    .put("username",loginUser.getUsername())
                                                                    .put("id",loginUser.getUuid())
                                                                    .put("type",loginUser.getType())
                                                                    .put("avatar",loginUser.getAvatar())
                                                                    .put("post",loginUser.getPostnumber())
                                                                    .map()
            );
        }catch (UnknownAccountException e) {

            return Result.fail("您输入的用户名或密码有误，请重新输入");
        }catch (IncorrectCredentialsException e){
            return Result.fail("您输入的用户名或密码有误，请重新输入");
        }
    }

    @PostMapping("/add")
    public Result add(@Validated @RequestBody(required = false) User user) throws Exception {

        /* @Description: 得到的密码先进行加密访问数据库,@Param:  */
        String password = DesAesUtil.desaes(user.getPassword());

        //判断数据库是否存在相同名字的用户
        String name = user.getUsername();
        User user1 = userMapper.selectByUsername(name);
        if (user1 != null){
            return Result.fail("你的用户名已经被注册！");
        }else {
            user.setPassword(password);
            int insert = userMapper.insert(user);
            if (insert != 0) {

                System.out.println("添加成功");
                return Result.success(200,"success",insert);
            } else {
                return Result.fail("注册失败");
            }
        }

    }

    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return  Result.success(null);
    }



}
